# -*- coding: utf-8 -*-
#
# File: ibictn.py
#
# Copyright (c) 2007 by CTEC
# Generator: ArchGenXML Version 1.5.0
#            http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

__author__ = """CTEC <joaojoao@gmail.com>"""
__docformat__ = 'plaintext'


from Products.CMFCore.utils import getToolByName
from Products.CMFCore.WorkflowTool import addWorkflowFactory
from Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition
from Products.ExternalMethod.ExternalMethod import ExternalMethod
from Products.ibictn.config import *

##code-section create-workflow-module-header #fill in your manual code here
##/code-section create-workflow-module-header


productname = 'ibictn'

def setupformulario_workflow(self, workflow):
    """Define the formulario_workflow workflow.
    """
    # Add additional roles to portal
    portal = getToolByName(self,'portal_url').getPortalObject()
    data = list(portal.__ac_roles__)
    for role in ['Provedor', 'Aprovador']:
        if not role in data:
            data.append(role)
    portal.__ac_roles__ = tuple(data)

    workflow.setProperties(title='formulario_workflow')

    ##code-section create-workflow-setup-method-header #fill in your manual code here
    ##/code-section create-workflow-setup-method-header


    for s in ['Rejeitado', 'Atendido', 'Aceito', 'Pendente', 'Elaboracao']:
        workflow.states.addState(s)

    for t in ['rejeitar', 'Devolver', 'Atender', 'aprovar', 'Nao_Aceitar', 'Tornar_Pendente', 'Enviar', 'Nao_ Atender']:
        workflow.transitions.addTransition(t)

    for v in ['review_history', 'comments', 'time', 'actor', 'action']:
        workflow.variables.addVariable(v)

    workflow.addManagedPermission('View')
    workflow.addManagedPermission('Modify portal content')
    workflow.addManagedPermission('ibictn: Ler campo')
    workflow.addManagedPermission('ibictn: Escrever campo')
    workflow.addManagedPermission('Access contents information')

    for l in ['para-atender', 'para-aceitar']:
        if not l in workflow.worklists.objectValues():
            workflow.worklists.addWorklist(l)

    ## Initial State

    workflow.states.setInitialState('Elaboracao')

    ## States initialization

    stateDef = workflow.states['Rejeitado']
    stateDef.setProperties(title="""Rejeitado""",
                           transitions=['Tornar_Pendente'])
    stateDef.setPermission('View',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])
    stateDef.setPermission('Modify portal content',
                           0,
                           ['Manager'])
    stateDef.setPermission('ibictn: Ler campo',
                           0,
                           ['Manager'])
    stateDef.setPermission('ibictn: Escrever campo',
                           0,
                           ['Manager'])
    stateDef.setPermission('Access contents information',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])

    stateDef = workflow.states['Atendido']
    stateDef.setProperties(title="""Atendido""",
                           transitions=[])
    stateDef.setPermission('View',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])
    stateDef.setPermission('Modify portal content',
                           0,
                           ['Manager'])
    stateDef.setPermission('ibictn: Ler campo',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])
    stateDef.setPermission('ibictn: Escrever campo',
                           0,
                           ['Manager'])
    stateDef.setPermission('Access contents information',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])

    stateDef = workflow.states['Aceito']
    stateDef.setProperties(title="""Aprovado""",
                           transitions=['rejeitar', 'Nao_ Atender', 'Atender'])
    stateDef.setPermission('View',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])
    stateDef.setPermission('Modify portal content',
                           0,
                           ['Provedor', 'Manager'])
    stateDef.setPermission('ibictn: Ler campo',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])
    stateDef.setPermission('ibictn: Escrever campo',
                           0,
                           ['Provedor', 'Manager'])
    stateDef.setPermission('Access contents information',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])

    stateDef = workflow.states['Pendente']
    stateDef.setProperties(title="""Pendente""",
                           transitions=['Devolver', 'Nao_Aceitar', 'aprovar'])
    stateDef.setPermission('View',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])
    stateDef.setPermission('Modify portal content',
                           0,
                           ['Aprovador', 'Manager'])
    stateDef.setPermission('ibictn: Ler campo',
                           0,
                           ['Aprovador', 'Manager'])
    stateDef.setPermission('ibictn: Escrever campo',
                           0,
                           ['Aprovador', 'Manager'])
    stateDef.setPermission('Access contents information',
                           0,
                           ['Owner', 'Aprovador', 'Provedor', 'Manager'])

    stateDef = workflow.states['Elaboracao']
    stateDef.setProperties(title="""Em Elaboração""",
                           transitions=['Enviar'])
    stateDef.setPermission('View',
                           0,
                           ['Owner', 'Aprovador', 'Manager'])
    stateDef.setPermission('Modify portal content',
                           0,
                           ['Owner', 'Manager'])
    stateDef.setPermission('ibictn: Ler campo',
                           0,
                           ['Manager'])
    stateDef.setPermission('ibictn: Escrever campo',
                           0,
                           ['Manager'])
    stateDef.setPermission('Access contents information',
                           0,
                           ['Owner', 'Aprovador', 'Manager'])

    ## Transitions initialization

    ## Creation of workflow scripts
    for wf_scriptname in ['sendDelvolvidoPendenteMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['rejeitar']
    transitionDef.setProperties(title="""Devolver""",
                                new_state_id="""Pendente""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendDelvolvidoPendenteMail""",
                                actbox_name="""Devolver""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Provedor;Manager'},
                                )

    ## Creation of workflow scripts
    for wf_scriptname in ['sendDevolvidoMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['Devolver']
    transitionDef.setProperties(title="""Devolver""",
                                new_state_id="""Elaboracao""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendDevolvidoMail""",
                                actbox_name="""Devolver""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Aprovador; Manager'},
                                )

    ## Creation of workflow scripts
    for wf_scriptname in ['sendAtendidoMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['Atender']
    transitionDef.setProperties(title="""Atender""",
                                new_state_id="""Atendido""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendAtendidoMail""",
                                actbox_name="""Atender""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Provedor;Manager'},
                                )

    ## Creation of workflow scripts
    for wf_scriptname in ['sendAceitoMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['aprovar']
    transitionDef.setProperties(title="""aprovar""",
                                new_state_id="""Aceito""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendAceitoMail""",
                                actbox_name="""aprovar""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Aprovador; Manager'},
                                )

    ## Creation of workflow scripts
    for wf_scriptname in ['sendRejeitadoMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['Nao_Aceitar']
    transitionDef.setProperties(title="""Não Aprovar""",
                                new_state_id="""Rejeitado""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendRejeitadoMail""",
                                actbox_name="""Não Aprovar""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Aprovador; Manager'},
                                )

    transitionDef = workflow.transitions['Tornar_Pendente']
    transitionDef.setProperties(title="""Tornar Pendente""",
                                new_state_id="""Pendente""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""""",
                                actbox_name="""Tornar Pendente""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Aprovador; Manager'},
                                )

    ## Creation of workflow scripts
    for wf_scriptname in ['sendPedenteMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['Enviar']
    transitionDef.setProperties(title="""Enviar""",
                                new_state_id="""Pendente""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendPedenteMail""",
                                actbox_name="""Enviar""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Owner'},
                                )

    ## Creation of workflow scripts
    for wf_scriptname in ['sendRejeitadoMail']:
        if not wf_scriptname in workflow.scripts.objectIds():
            workflow.scripts._setObject(wf_scriptname,
                ExternalMethod(wf_scriptname, wf_scriptname,
                productname + '.formulario_workflow_scripts',
                wf_scriptname))

    transitionDef = workflow.transitions['Nao_ Atender']
    transitionDef.setProperties(title="""Não Atender""",
                                new_state_id="""Rejeitado""",
                                trigger_type=1,
                                script_name="""""",
                                after_script_name="""sendRejeitadoMail""",
                                actbox_name="""Não Atender""",
                                actbox_url="""""",
                                actbox_category="""workflow""",
                                props={'guard_roles': 'Provedor;Manager'},
                                )

    ## State Variable
    workflow.variables.setStateVar('review_state')

    ## Variables initialization
    variableDef = workflow.variables['review_history']
    variableDef.setProperties(description="""Provides access to workflow history""",
                              default_value="""""",
                              default_expr="""state_change/getHistory""",
                              for_catalog=0,
                              for_status=0,
                              update_always=0,
                              props={'guard_permissions': 'Request review; Review portal content'})

    variableDef = workflow.variables['comments']
    variableDef.setProperties(description="""Comments about the last transition""",
                              default_value="""""",
                              default_expr="""python:state_change.kwargs.get('comment', '')""",
                              for_catalog=0,
                              for_status=1,
                              update_always=1,
                              props=None)

    variableDef = workflow.variables['time']
    variableDef.setProperties(description="""Time of the last transition""",
                              default_value="""""",
                              default_expr="""state_change/getDateTime""",
                              for_catalog=0,
                              for_status=1,
                              update_always=1,
                              props=None)

    variableDef = workflow.variables['actor']
    variableDef.setProperties(description="""The ID of the user who performed the last transition""",
                              default_value="""""",
                              default_expr="""user/getId""",
                              for_catalog=0,
                              for_status=1,
                              update_always=1,
                              props=None)

    variableDef = workflow.variables['action']
    variableDef.setProperties(description="""The last transition""",
                              default_value="""""",
                              default_expr="""transition/getId|nothing""",
                              for_catalog=0,
                              for_status=1,
                              update_always=1,
                              props=None)

    ## Worklists Initialization

    worklistDef = workflow.worklists['para-atender']
    worklistStates = ['Aceito']
    actbox_url = "%(portal_url)s/search?review_state=" + "&review_state=".join(worklistStates)
    worklistDef.setProperties(description="Reviewer tasks",
                              actbox_name="Pending (%(count)d)",
                              actbox_url=actbox_url,
                              actbox_category="global",
                              props={'guard_permissions': 'Review portal content',
                                     'guard_roles': 'Provedor;Manager',
                                     'var_match_review_state': ';'.join(worklistStates)})
    worklistDef = workflow.worklists['para-aceitar']
    worklistStates = ['Pendente']
    actbox_url = "%(portal_url)s/search?review_state=" + "&review_state=".join(worklistStates)
    worklistDef.setProperties(description="Reviewer tasks",
                              actbox_name="Pending (%(count)d)",
                              actbox_url=actbox_url,
                              actbox_category="global",
                              props={'guard_permissions': 'Review portal content',
                                     'guard_roles': 'Aprovador;Manager',
                                     'var_match_review_state': ';'.join(worklistStates)})

    # WARNING: below protected section is deprecated.
    # Add a tagged value 'worklist' with the worklist name to your state(s) instead.

    ##code-section create-workflow-setup-method-footer #fill in your manual code here
    ##/code-section create-workflow-setup-method-footer



def createformulario_workflow(self, id):
    """Create the workflow for ibictn.
    """

    ob = DCWorkflowDefinition(id)
    setupformulario_workflow(self, ob)
    return ob

addWorkflowFactory(createformulario_workflow,
                   id='formulario_workflow',
                   title='formulario_workflow')

##code-section create-workflow-module-footer #fill in your manual code here
##/code-section create-workflow-module-footer

